import json
import datetime
from rest_framework import views, permissions, response, status
from apps.nav.models import NavModel
from apps.nav.serializers import NavModelSerializer
from utils.response import data_response

from apps.api.project.models import ProjectModel
from apps.api.interface.models import InterfaceModel
from apps.api.testcase.models import TestCaseModel
from apps.api.suite.models import SuiteModel
from apps.basic.environment.models import EnvironmentModel
from apps.product.report.models import ReportModel


class NavView(views.APIView):
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request):
        qs = NavModel.objects.all()
        serializer = NavModelSerializer(instance=qs, many=True)
        f_data = []
        for item in serializer.data:
            item = dict(item)
            if item["pid"] == 0:
                item["children"] = []
                f_data.append(item)
        for f in f_data:
            for c_data in serializer.data:
                c_data = dict(c_data)
                if c_data["pid"] == f["id"]:
                    f["children"].append(c_data)
        result = data_response(data=f_data)
        return response.Response(result, status=status.HTTP_200_OK)

    def post(self, request):
        serializer = NavModelSerializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            serializer.save()
            result = data_response(data=serializer.data)
            return response.Response(result, status=status.HTTP_201_CREATED)


class SummaryView(views.APIView):
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request):
        project_count = ProjectModel.objects.filter(is_delete=0).count()
        interface_count = InterfaceModel.objects.filter(is_delete=0).count()
        testcase_count = TestCaseModel.objects.filter(is_delete=0).count()
        testsuite_count = SuiteModel.objects.filter(is_delete=0).count()
        environment_count = EnvironmentModel.objects.filter(is_delete=0).count()
        reports = ReportModel.objects.filter(is_delete=0)
        testcase_summary = [
            {"type": "success", "total": 0},
            {"type": "fail", "total": 0},
            {"type": "error", "total": 0},
            {"type": "skip", "total": 0},
        ]
        report_summary = {
            "success": 0,
            "fail": 0,
            "time": [],
            "detail": []
        }
        for report in reports:
            report = json.loads(report.summary)
            if report["success"] == True:
                report_summary["success"] += 1
            else:
                report_summary["fail"] += 1
            start_time = datetime.datetime.fromtimestamp(int(report["time"]["start_at"])).strftime('%Y-%m-%d %H:%M:%S')
            report_summary["time"].append(start_time)
            report_detail = { "value": "", "name": "", "success": 0, "fail": 0, "error": 0, "skip": 0, "time": ''}
            report_detail["value"] = report["stat"]["teststeps"]["total"]
            report_detail["name"] = report["html_report_name"]
            report_detail["success"] = report["stat"]["teststeps"]["successes"]
            report_detail["fail"] = report["stat"]["teststeps"]["failures"]
            report_detail["error"] = report["stat"]["teststeps"]["errors"]
            report_detail["skip"] = report["stat"]["teststeps"]["skipped"]
            report_detail["time"] = start_time
            report_summary["detail"].append(report_detail)
            testcase_summary[0]["total"] += report["stat"]["teststeps"]["successes"]
            testcase_summary[1]["total"] += report["stat"]["teststeps"]["failures"]
            testcase_summary[2]["total"] += report["stat"]["teststeps"]["errors"]
            testcase_summary[3]["total"] += report["stat"]["teststeps"]["skipped"]

        statistics = {
            "global_statistics": {
                "project_count": project_count,
                "interface_count": interface_count,
                "testcase_count": testcase_count,
                "testsuite_count": testsuite_count,
                "environment_count": environment_count,
                "report_count": reports.count()
            },
            "report_statistics": report_summary,
            "testcase_statistics": testcase_summary
        }
        result = data_response(data=statistics)
        return response.Response(result, status=status.HTTP_200_OK)
